﻿using SageKing.Application.AspNetCore.SqlSugar.Extensions;
using System.Linq.Expressions;

namespace SageKing.Application.AspNetCore.SqlSugar.Service;

/// <summary>
/// SageKing消息结构表服务 
/// </summary>
/// <param name="repository"></param>
public class SysSageKingMessageService(SageKingRepository<SysSageKingMessage> repository, SageKingRepository<SysSageKingMessageAttribute> repositoryatt)
    : BaseService<SysSageKingMessage>(repository)
{
    /// <summary>
    /// 获取one
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取one")]
    public virtual async Task<SysSageKingMessage> GetOneWithChild(Expression<Func<SysSageKingMessage, bool>> wherefunc)
    {
        var result = await repository.AsQueryable().Includes(a => a.Children).Where(wherefunc).FirstAsync();
        return result;
    }

    /// <summary>
    /// 获取数据 pos
    /// </summary>
    /// <param name="name"></param>
    /// <param name="version"></param>
    /// <returns></returns>
    public async Task<Dictionary<DataStreamTypeEnum, Dictionary<string, byte>>> GetPosDic(string name, long version)
    {
        var getFirst = await GetOneWithChild(a => a.Name == name && a.Version == version);
        if (getFirst == null || !getFirst.Children.HasItem())
        {
            return new Dictionary<DataStreamTypeEnum, Dictionary<string, byte>>();
        }
        return getFirst.GetPosDic();
    }

    /// <summary>
    /// 更新 版本
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    [DisplayName("更新")]
    public virtual async Task<int> UpdateVersion(SysSageKingMessage entity, Expression<Func<SysSageKingMessage, object>> updateColumns = null)
    {
        if (updateColumns == null)
        {
            updateColumns = (SysSageKingMessage a) => new { a.Version, a.UpdateTime };
        }
        return await UpdateWithOptLock(entity, updateColumns);
    }
}
